// 定义用户相关仓库数据
import { defineStore } from "pinia";
// @ts-ignore
import { reqCode, reqUserLogin } from "@/api/hospital";
import type {
  LoginData,
  UserLoginResponseData,
  UserInfo,
} from "@/api/hospital/type";
import type { UserState } from "./interface";

const useUserStore = defineStore("User",{
    state: (): UserState => {
      return {
        // 用于控制登录组件dialog的显示与隐藏
        visible: false,
        // 验证码
        code: "",
        userInfo: ({} as UserInfo) || {},
      };
    },
    actions: {
      // 获取验证码的方法
      async getCode(phone: string) {
        // 在向服务器携带手机号码，获取验证码
        let result: any = await reqCode(phone);
        if (result.code == 200) {
          this.code = result.data;
          return "ok";
        } else {
          return Promise.reject(new Error(result.message));
        }
      },
      async userLogin(data: LoginData) {
        // 登录请求
        let result: UserLoginResponseData = await reqUserLogin(data);
        console.log(result);
        if (result.code == 200) {
          this.userInfo = result.data;
          // 返回一个成功的Promise
          return "ok";
        } else {
          return Promise.reject(new Error(result.message));
        }
      },
      // 清空userInfo数据
      clearUserInfo(){
        this.userInfo={name:'',token:''}
      },
      // 查询微信扫码的接口
      queryState(){
        // 开启定时器 每隔一段时间问本地存储是否有用户信息
        let timer=setInterval(()=>{
          // if(this.getToken){
            this.visible=false
            // this.userInfo=this.getToken
            clearInterval(timer)
          // }
        },1000)
      }
    },
    getters: {},
    persist: true,
  }
);

export default useUserStore;
